package com.zb.kc.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.zb.kc.commonutils.ExceptionUtil;
import com.zb.kc.commonutils.R;
import com.zb.kc.servicebase.exceptionhandler.KgcException;
import com.zb.kc.vod.service.VodService;
import com.zb.kc.vod.utils.ConstantVodUtils;
import com.zb.kc.vod.utils.InitVodCilent;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.ws.rs.PathParam;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/eduvod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    // 上传视频到阿里云
    @PostMapping
    @ApiOperation(value = "上传视频到阿里云")
    public R uploadAlyVideo(MultipartFile file) {
        // 返回上传视频id
        String videoId = vodService.uploadAlyVideo(file);
        return R.ok().data("videoId", videoId);
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "根据阿里云的视频id删除阿里云上视频")
    public R removeAlyVideo(@PathVariable("id") String id) {
        vodService.deleteVideo(id);
        return R.ok().message("删除成功");
    }

    /**
     * 阿里云删除多个视频
     *
     * @param videIdList
     * @return
     */
    @DeleteMapping("delete-batch")
    public R deleteBathch(@RequestParam("videoIdList") List<String> videIdList) {
        vodService.removeMoreAlyVideo(videIdList);
        return R.ok();
    }

    // 根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
            // 创建初始化对象
            DefaultAcsClient client = InitVodCilent.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            // 创建获取凭证的request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            // 向request中设置视频id
            request.setVideoId(id);
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth", playAuth);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionUtil.getMessage(e);
            throw new KgcException(20001, "获取凭证失败");
        }
    }

}
